#include "file_browser.h"
#include "ui_file_browser.h"
#include "unitls/globalsignalmgr.h"

File_Browser::File_Browser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::File_Browser),
    tree_root_item(nullptr)
{
    ui->setupUi(this);
    Init_UI();
}

File_Browser::~File_Browser()
{
    delete ui;
}

void File_Browser::Init_UI()
{
    QIcon img(":/images/file_browser_hide.png");
    ui->button_hide->setIcon(img);
    ui->button_hide->setToolTip("hide window F6");
    GlobalSignalMgr::get_instance()->attach(SignalType::SIG_SET_FLODER, this, SLOT(on_floder_setted(QString)));
    QVariant current_path = Config_file().get("global", "data_floder");
    root_path = current_path.toString();
    ui->treeView->header()->hide();
    model = new QStandardItemModel(ui->treeView);
    ui->treeView->setModel(model);
    ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->treeView, &QTreeView::customContextMenuRequested, this, &File_Browser::slot_right_click_event );
    Init_floder_tree(root_path, tree_root_item);

}

void File_Browser::on_button_hide_clicked()
{
    hide();
    qInfo("file browser hide clicked");
    GlobalSignalMgr::get_instance()->notify(SignalType::SIG_RELAYOUT_WINDOW);
}

void File_Browser::on_floder_setted(QString floder)
{
    if (tree_root_item){
        ui->treeView->itemDelegateForRow(0);
        model = new QStandardItemModel(ui->treeView);
        tree_root_item = nullptr;
    }
    Init_floder_tree(floder, nullptr);
}

void File_Browser::on_treeView_doubleClicked(QModelIndex file_inded)
{
    QMap<int, QVariant> node_data =model->itemData(file_inded);
    QString full_path = node_data[257].toString();
    QFileInfo fi(full_path);
    if(fi.isFile()){
        GlobalSignalMgr::get_instance()->notify(SignalType::SIG_FILE_ADD_EDIT_STRING, full_path);
    }
    else{
        qInfo(full_path.toStdString().c_str());
    }

}


void File_Browser::resizeEvent(QResizeEvent *event)
{
    QSize size = event->size();
    int x = this->x();
    int y = this->y();
    ui->button_hide->move(x + size.width() - ui->button_hide->width(), y);
    ui->treeView->move(x, y + ui->button_hide->height());
    ui->treeView->resize(size.width(), size.height() - ui->button_hide->height());
}

void File_Browser::slot_right_click_event(const QPoint &pos)
{
    QMenu menu;
    QModelIndex curIndex = ui->treeView->currentIndex();
    QString point_path = model->itemData(curIndex)[257].toString();
    QFileInfo tmp_file(point_path);
    if(!curIndex.parent().isValid()){
        menu.addAction(QString(tr("关闭知识库")),this, SLOT(slot_remove_root_dir()));
    }
    else if (tmp_file.isDir()){
        menu.addAction(QString(tr("重命名")), this, SLOT(slot_rename_dir()));
        menu.addAction(QString(tr("删除目录")), this, SLOT(slot_delete_dir()));
    }
    else{
        menu.addAction(QString(tr("重命名")), this, SLOT(slot_rename_file()));
        menu.addAction(QString(tr("删除文件")), this, SLOT(slot_delete_file()));
    }
    menu.exec(QCursor::pos());
}

void File_Browser::slot_rename_file()
{
    QModelIndex curIndex = ui->treeView->currentIndex();
    QMap<int,QVariant> node_map = model->itemData(curIndex);
    QString file_name = node_map.values()[0].toString();
    QString full_file_name = node_map[257].toString();
    bool ok = false;
    QString new_file_name = QInputDialog::getText(this, tr("重命名"),tr("请输入文件名"), QLineEdit::Normal, 0, &ok);
    if (ok && !new_file_name.isEmpty()){
        QString replace_str = replace_file_name(full_file_name,new_file_name);
        QString full_new_file_path = get_new_file_name_from_replace_str(replace_str);
        node_map[0] = new_file_name;
        node_map[257] = full_new_file_path;
        model->setItemData(curIndex,node_map);
        GlobalSignalMgr::get_instance()->notify(SignalType::SIG_FILE_NAME_CHANGED_STRING, replace_str);
    }

}

void File_Browser::slot_rename_dir()
{

}

void File_Browser::slot_delete_file()
{

}

void File_Browser::slot_delete_dir()
{

}

void File_Browser::slot_remove_root_dir()
{
    model->clear();
    root_path = "";
    tree_root_item = nullptr;
}



int File_Browser::get_child_index_from_parent(QModelIndex parent, QString child_val) const
{
    int col_index = -1;
    for(int i = 0;;i++){
        QModelIndex tmp = parent.child(i,0);
        if(!tmp.isValid()){
            break;
        }
        if(!model->itemData(tmp)[257].toString().compare(child_val)){
            col_index = i;
            break;
        }
    }
    return col_index;
}





void File_Browser::Init_floder_tree(QString& path, MStandardItem* root)
{
    QString current_path = path;
    if(!current_path.length()){
        return;
    }
    if(!root){
        QString node_name = get_file_name_use_path(path);
        tree_root_item = new MStandardItem(node_name);
        tree_root_item->setData(path);
        tree_root_item->setEditable(false);
        tree_root_item->setIcon(get_file_icon(path));
        model->appendRow(tree_root_item);
        Init_floder_tree(path, tree_root_item);
    }
    else{
        QDir  dir(path);
        dir.setSorting(QDir::Type);
        QFileInfoList list = dir.entryInfoList();
        //2. makesure create
        for (int i = 0; i < list.size(); ++i){
            QFileInfo fileInfo= list.at(i);
            QString file_name = fileInfo.fileName();
            QString full_file_name = fileInfo.absoluteFilePath();
            if (!(file_name.compare(".")&&file_name.compare(".."))){continue;}
            MStandardItem* next_file = nullptr;
            next_file = new MStandardItem(file_name);
            next_file->setEditable(false);
            next_file->setData(full_file_name);
            next_file->setIcon(get_file_icon(full_file_name));
            child_list.append(next_file);
            root->appendRow(next_file);
            if (fileInfo.isDir()){
                Init_floder_tree(full_file_name, next_file);
            }

        }
    }

}

